/**
 * @author 艾尼亚尔
 * @date 2025/5/19
 * @description
 */
import axios from 'axios';
import type {AxiosRequestConfig, AxiosResponse} from 'axios'
import {AxiosService} from './AxiosService';
import type {AxiosTransform} from './transformAxios';
import type {CreateAxiosOptions, Result} from './type';
import {isUrl,isString,joinTimestamp,formatRequestDate} from './help.ts'

const transformAxios: AxiosTransform = {
    // 请求之前处理config
    beforeRequestHook(config, options) {
        const {urlPrefix,joinTime=true} = options;
        const isUrlStr = isUrl(config.url as string);
        if (!isUrlStr) {
            config.url = `${urlPrefix}${config.url}`;
        }
        const params = config.params || {};
        const data = config.data || false;
        if (config.method?.toUpperCase() === "GET") {
            if (!isString(params)) {
                // 给 get 请求加上时间戳参数，避免从缓存中拿数据。
                config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
            } else {
                // 兼容restful风格
                config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
                config.params = undefined;
            }
        } else {
            if (!isString(params)) {
                formatRequestDate(params);
                if (Reflect.has(config, 'data') && config.data && Object.keys(config.data).length > 0) {
                    config.data = data;
                    config.params = params;
                } else {
                    config.data = params;
                    config.params = undefined;
                }
            } else {
                // 兼容restful风格
                config.url = config.url + params;
                config.params = undefined;
            }
        }
        return config
    },
    //请求拦截器处理
    requestInterceptors(config: AxiosRequestConfig, options: CreateAxiosOptions) {
        //token
        return config
    },
    //响应拦截器
    transformResponseData(res: AxiosResponse<Result>, options: any) {
        return res
    },
    //响应错误处理
    responseInterceptorsCatch(error: any) {
        const {response, code, message} = error || {};
        //自行处理
        const isCancel = axios.isCancel(error);
        if (!isCancel) {
            console.log('die')
            console.log(code)
        } else {
            console.warn(error, '请求被取消！');
        }
        return Promise.reject(response?.data);
    },
}


const defaultOptions: CreateAxiosOptions = {
    urlPrefix: '/api',
    timeout: 10 * 1000,
    headers: {'Content-Type': 'application/json;charset=UTF-8'},
    transform: transformAxios,
};

export const http = new AxiosService(defaultOptions);
